package com.s3.stack;

public class SampleBrowser {

	public static void main(String[] args) {
		SampleBrowser browser = new SampleBrowser();
		browser.openURL("http://www.soso.com");
		browser.openURL("http://www.qq.com/111");
		browser.openURL("http://www.qq.com/222");
		browser.back();
		browser.forward();
		browser.back();
		browser.openURL("http://news.qq.com");
		browser.forward();
		browser.back();
		browser.back();
	}

	private LinkedStack forwardStack = new LinkedStack(100);
	private LinkedStack backStack = new LinkedStack(100);

	public void openURL(String url) {
		this.loadURL(url);
		this.forwardStack.push(url);
		this.backStack.clear();
	}

	private void loadURL(String url) {
		System.out.println("load ..." + url);
	}

	public void back() {
		// 如果 forwardStack 不为空才能继续
		if (this.canBack()) {
			this.backStack.push(this.forwardStack.pop());
			this.loadURL((String) this.forwardStack.getTopData());
		} else {
			System.out.println("can not back");
		}
	}

	public void forward() {
		// 如果 forwardStack 不为空才能继续
		if (this.canForward()) {
			Object data = this.backStack.pop();
			this.forwardStack.push(data);
			this.loadURL((String) data);
		} else {
			System.out.println("can not forward");
		}
	}

	private boolean canBack() {
		// 当前进栈里面至少有 2 个元素的时候
		return forwardStack.getUsedLength() >= 2;
	}

	private boolean canForward() {
		return !this.backStack.isEmpty();
	}
}
